package com.ruoyi.web.controller.system;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.user.mapper.TbUserMapper;
import com.ruoyi.user.mapper.TbUser1Mapper;
import com.ruoyi.request.mapper.TbMatchmakingRequestMapper;
import com.ruoyi.arrangement.mapper.TbDateArrangementMapper;
import com.ruoyi.performance.mapper.TbMatchmakerPerformanceMapper;
import com.ruoyi.application.mapper.TbMatchmakerApplicationMapper;
import com.ruoyi.feedback.mapper.TbDateFeedbackMapper;

import java.util.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 首页
 *
 * @author ruoyi
 */
@RestController
public class SysIndexController
{
    /** 系统基础配置 */
    @Autowired
    private RuoYiConfig ruoyiConfig;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private TbUser1Mapper tbUser1Mapper;

    @Autowired
    private TbMatchmakingRequestMapper tbMatchmakingRequestMapper;

    @Autowired
    private TbDateArrangementMapper tbDateArrangementMapper;

    @Autowired
    private TbMatchmakerPerformanceMapper tbMatchmakerPerformanceMapper;

    @Autowired
    private TbMatchmakerApplicationMapper tbMatchmakerApplicationMapper;

    @Autowired
    private TbDateFeedbackMapper tbDateFeedbackMapper;

    /**
     * 访问首页，提示语
     */
    @RequestMapping("/")
    public String index()
    {
        return StringUtils.format("欢迎使用{}后台管理框架，当前版本：v{}，请通过前端地址访问。", ruoyiConfig.getName(), ruoyiConfig.getVersion());
    }

    /**
     * 获取良缘平台统计数据
     */
    @GetMapping("/dashboard/statistics")
    public AjaxResult getDashboardStatistics()
    {
        Map<String, Object> data = new HashMap<>();

        // 平台核心数据
        Map<String, Object> coreStats = new HashMap<>();
        coreStats.put("totalUsers", getTotalUsers());
        coreStats.put("activeUsers", getActiveUsers());
        coreStats.put("successfulMatches", getSuccessfulMatches());
        coreStats.put("gameInteractions", getGameInteractions());
        coreStats.put("chatMessages", getChatMessages());
        coreStats.put("platformRevenue", getPlatformRevenue());

        // 实时数据
        Map<String, Object> realtimeStats = new HashMap<>();
        realtimeStats.put("onlineUsers", getOnlineUsers());
        realtimeStats.put("todayNewUsers", getTodayNewUsers());
        realtimeStats.put("todayMatches", getTodayMatches());
        realtimeStats.put("todayGamePlays", getTodayGamePlays());

        // 用户性别年龄分布
        Map<String, Object> userDemographics = getUserDemographics();

        // 地区用户分布
        List<Map<String, Object>> regionDistribution = getRegionDistribution();

        // 平台功能使用统计
        List<Map<String, Object>> featureUsage = getFeatureUsage();

        // 匹配成功率趋势
        List<Map<String, Object>> matchSuccessTrend = getMatchSuccessTrend();

        // 用户活跃度分析
        List<Map<String, Object>> userActivityAnalysis = getUserActivityAnalysis();

        // 热门游戏排行
        List<Map<String, Object>> popularGames = getPopularGames();

        // 实时动态
        List<Map<String, Object>> realtimeActivities = getRealtimeActivities();

        // 社交网络数据
        Map<String, Object> socialNetworkData = getSocialNetworkData();

        data.put("coreStats", coreStats);
        data.put("realtimeStats", realtimeStats);
        data.put("userDemographics", userDemographics);
        data.put("regionDistribution", regionDistribution);
        data.put("featureUsage", featureUsage);
        data.put("matchSuccessTrend", matchSuccessTrend);
        data.put("userActivityAnalysis", userActivityAnalysis);
        data.put("popularGames", popularGames);
        data.put("realtimeActivities", realtimeActivities);
        data.put("socialNetworkData", socialNetworkData);

        return AjaxResult.success(data);
    }

    /**
     * 获取平台用户总数
     */
    private Long getTotalUsers() {
        try {
            Long count = (long) tbUserMapper.selectTbUserList(null).size();
            return count > 0 ? count : 2580000L; // 如果有真实数据则使用，否则使用模拟数据
        } catch (Exception e) {
            return 2580000L; // 模拟数据 - 258万用户
        }
    }

    /**
     * 获取活跃用户数
     */
    private Long getActiveUsers() {
        try {
            // 查询最近30天活跃用户
            return 1850000L; // 模拟数据 - 185万活跃用户
        } catch (Exception e) {
            return 1850000L;
        }
    }

    /**
     * 获取成功匹配数
     */
    private Long getSuccessfulMatches() {
        try {
            // 查询所有成功匹配的数量
            Long count = (long) tbDateArrangementMapper.selectTbDateArrangementList(null).size();
            return count > 0 ? count : 456789L; // 如果有真实数据则使用，否则使用模拟数据
        } catch (Exception e) {
            return 456789L;
        }
    }

    /**
     * 获取游戏互动次数
     */
    private Long getGameInteractions() {
        try {
            // 查询所有游戏互动次数
            return 12580000L; // 模拟数据 - 1258万次游戏互动
        } catch (Exception e) {
            return 12580000L;
        }
    }

    /**
     * 获取聊天消息数
     */
    private Long getChatMessages() {
        try {
            // 查询所有聊天消息数
            return 89650000L; // 模拟数据 - 8965万条消息
        } catch (Exception e) {
            return 89650000L;
        }
    }

    /**
     * 获取平台收入
     */
    private BigDecimal getPlatformRevenue() {
        try {
            // 查询平台总收入
            return new BigDecimal("15680000.00"); // 模拟数据 - 1568万收入
        } catch (Exception e) {
            return new BigDecimal("15680000.00");
        }
    }

    /**
     * 获取在线用户数
     */
    private Long getOnlineUsers() {
        return 125000L; // 模拟数据 - 12.5万在线用户
    }

    /**
     * 获取今日新用户数
     */
    private Long getTodayNewUsers() {
        return 3580L; // 模拟数据 - 今日新增3580用户
    }

    /**
     * 获取今日匹配数
     */
    private Long getTodayMatches() {
        return 1250L; // 模拟数据 - 今日成功匹配1250对
    }

    /**
     * 获取今日游戏次数
     */
    private Long getTodayGamePlays() {
        return 45600L; // 模拟数据 - 今日游戏互动45600次
    }

    /**
     * 测试数据库连接和数据
     */
    private void testDatabaseData() {
        try {
            // 测试基本的用户数据查询
            System.out.println("=== 开始测试数据库连接 ===");
            
            // 查询用户总数
            List<com.ruoyi.user.domain.TbUser> allUsers = tbUser1Mapper.selectTbUserList(new com.ruoyi.user.domain.TbUser());
            System.out.println("用户总数: " + (allUsers != null ? allUsers.size() : 0));
            
            if (allUsers != null && !allUsers.isEmpty()) {
                System.out.println("前几个用户的性别信息:");
                for (int i = 0; i < Math.min(5, allUsers.size()); i++) {
                    com.ruoyi.user.domain.TbUser user = allUsers.get(i);
                    System.out.println("用户ID: " + user.getUserId() + ", 性别: " + user.getGender());
                }
                
                // 检查用户是否有关联的详细资料
                System.out.println("检查用户详细资料:");
                for (int i = 0; i < Math.min(3, allUsers.size()); i++) {
                    com.ruoyi.user.domain.TbUser user = allUsers.get(i);
                    if (user.getTbUserProfileList() != null && !user.getTbUserProfileList().isEmpty()) {
                        com.ruoyi.user.domain.TbUserProfile profile = user.getTbUserProfileList().get(0);
                        System.out.println("用户ID: " + user.getUserId() + ", 年龄: " + profile.getAge());
                    } else {
                        System.out.println("用户ID: " + user.getUserId() + ", 没有详细资料");
                    }
                }
            }
            
            System.out.println("=== 数据库连接测试完成 ===");
        } catch (Exception e) {
            System.out.println("数据库连接测试异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 获取用户人口统计数据
     */
    private Map<String, Object> getUserDemographics() {
        Map<String, Object> data = new HashMap<>();
        
        // 先测试数据库连接和数据
        testDatabaseData();

        // 性别分布 - 使用真实数据
        List<Map<String, Object>> genderDistribution = new ArrayList<>();
        try {
            System.out.println("开始查询性别分布数据...");
            List<Map<String, Object>> realGenderData = tbUser1Mapper.selectGenderDistribution();
            System.out.println("性别分布查询结果: " + realGenderData);
            
            if (realGenderData != null && !realGenderData.isEmpty()) {
                genderDistribution = realGenderData;
                System.out.println("使用真实性别数据: " + genderDistribution);
            } else {
                System.out.println("没有真实性别数据，使用默认数据");
                // 如果没有真实数据，使用默认数据
                Map<String, Object> male = new HashMap<>();
                male.put("name", "男性用户");
                male.put("value", 1420000);
                male.put("percentage", 55.0);
                genderDistribution.add(male);

                Map<String, Object> female = new HashMap<>();
                female.put("name", "女性用户");
                female.put("value", 1160000);
                female.put("percentage", 45.0);
                genderDistribution.add(female);
            }
        } catch (Exception e) {
            System.out.println("查询性别分布数据异常: " + e.getMessage());
            e.printStackTrace();
            // 异常情况下使用默认数据
            Map<String, Object> male = new HashMap<>();
            male.put("name", "男性用户");
            male.put("value", 1420000);
            male.put("percentage", 55.0);
            genderDistribution.add(male);

            Map<String, Object> female = new HashMap<>();
            female.put("name", "女性用户");
            female.put("value", 1160000);
            female.put("percentage", 45.0);
            genderDistribution.add(female);
        }

        // 年龄分布 - 使用真实数据
        List<Map<String, Object>> ageDistribution = new ArrayList<>();
        try {
            System.out.println("开始查询年龄分布数据...");
            List<Map<String, Object>> realAgeData = tbUser1Mapper.selectAgeDistribution();
            System.out.println("年龄分布查询结果: " + realAgeData);
            
            if (realAgeData != null && !realAgeData.isEmpty()) {
                ageDistribution = realAgeData;
                System.out.println("使用真实年龄数据: " + ageDistribution);
            } else {
                System.out.println("没有真实年龄数据，使用默认数据");
                // 如果没有真实数据，使用默认数据
                String[] ageGroups = {"18-25岁", "26-30岁", "31-35岁", "36-40岁", "40岁以上"};
                int[] ageCounts = {580000, 920000, 680000, 280000, 120000};
                double[] agePercentages = {22.5, 35.7, 26.4, 10.9, 4.5};

                for (int i = 0; i < ageGroups.length; i++) {
                    Map<String, Object> ageGroup = new HashMap<>();
                    ageGroup.put("name", ageGroups[i]);
                    ageGroup.put("value", ageCounts[i]);
                    ageGroup.put("percentage", agePercentages[i]);
                    ageDistribution.add(ageGroup);
                }
            }
        } catch (Exception e) {
            System.out.println("查询年龄分布数据异常: " + e.getMessage());
            e.printStackTrace();
            // 异常情况下使用默认数据
            String[] ageGroups = {"18-25岁", "26-30岁", "31-35岁", "36-40岁", "40岁以上"};
            int[] ageCounts = {580000, 920000, 680000, 280000, 120000};
            double[] agePercentages = {22.5, 35.7, 26.4, 10.9, 4.5};

            for (int i = 0; i < ageGroups.length; i++) {
                Map<String, Object> ageGroup = new HashMap<>();
                ageGroup.put("name", ageGroups[i]);
                ageGroup.put("value", ageCounts[i]);
                ageGroup.put("percentage", agePercentages[i]);
                ageDistribution.add(ageGroup);
            }
        }

        data.put("genderDistribution", genderDistribution);
        data.put("ageDistribution", ageDistribution);

        return data;
    }

    /**
     * 获取平台功能使用统计
     */
    private List<Map<String, Object>> getFeatureUsage() {
        List<Map<String, Object>> data = new ArrayList<>();

        String[] features = {"聊天交友", "心动游戏", "视频通话", "语音聊天", "动态分享", "礼物赠送"};
        long[] usageCounts = {2580000L, 1850000L, 920000L, 1560000L, 680000L, 450000L};
        double[] usageRates = {100.0, 71.7, 35.7, 60.5, 26.4, 17.4};

        for (int i = 0; i < features.length; i++) {
            Map<String, Object> feature = new HashMap<>();
            feature.put("name", features[i]);
            feature.put("usageCount", usageCounts[i]);
            feature.put("usageRate", usageRates[i]);
            data.add(feature);
        }

        return data;
    }

    /**
     * 获取匹配成功率趋势
     */
    private List<Map<String, Object>> getMatchSuccessTrend() {
        List<Map<String, Object>> data = new ArrayList<>();
        String[] months = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月"};
        int[] totalMatches = {28000, 32000, 35000, 38000, 42000, 45000, 48000, 52000};
        int[] successfulMatches = {18200, 21600, 24500, 27360, 31080, 34650, 38400, 42640};
        double[] successRates = {65.0, 67.5, 70.0, 72.0, 74.0, 77.0, 80.0, 82.0};

        for (int i = 0; i < months.length; i++) {
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("month", months[i]);
            monthData.put("totalMatches", totalMatches[i]);
            monthData.put("successfulMatches", successfulMatches[i]);
            monthData.put("successRate", successRates[i]);
            data.add(monthData);
        }

        return data;
    }

    /**
     * 获取地区分布数据
     */
    private List<Map<String, Object>> getRegionDistribution() {
        List<Map<String, Object>> data = new ArrayList<>();

        String[] regions = {"北京", "上海", "广州", "深圳", "杭州", "成都", "武汉", "西安", "南京", "重庆"};
        int[] counts = {285000, 268000, 245000, 232000, 198000, 175000, 156000, 142000, 128000, 115000};
        double[] percentages = {11.0, 10.4, 9.5, 9.0, 7.7, 6.8, 6.0, 5.5, 5.0, 4.5};

        for (int i = 0; i < regions.length; i++) {
            Map<String, Object> regionData = new HashMap<>();
            regionData.put("name", regions[i]);
            regionData.put("value", counts[i]);
            regionData.put("percentage", percentages[i]);
            data.add(regionData);
        }

        return data;
    }

    /**
     * 获取用户活跃度分析
     */
    private List<Map<String, Object>> getUserActivityAnalysis() {
        List<Map<String, Object>> data = new ArrayList<>();

        String[] timeSlots = {"00-06", "06-12", "12-18", "18-24"};
        int[] activeUsers = {125000, 680000, 920000, 1450000};
        double[] activityRates = {4.8, 26.4, 35.7, 56.2};

        for (int i = 0; i < timeSlots.length; i++) {
            Map<String, Object> timeSlot = new HashMap<>();
            timeSlot.put("timeSlot", timeSlots[i]);
            timeSlot.put("activeUsers", activeUsers[i]);
            timeSlot.put("activityRate", activityRates[i]);
            data.add(timeSlot);
        }

        return data;
    }

    /**
     * 获取热门游戏排行
     */
    private List<Map<String, Object>> getPopularGames() {
        List<Map<String, Object>> data = new ArrayList<>();

        String[] gameNames = {"心动问答", "情侣默契", "真心话大冒险", "语音聊天室", "视频速配"};
        int[] playTimes = {3580000, 2850000, 2120000, 1680000, 1250000};
        double[] popularityRates = {100.0, 79.6, 59.2, 46.9, 34.9};

        for (int i = 0; i < gameNames.length; i++) {
            Map<String, Object> game = new HashMap<>();
            game.put("name", gameNames[i]);
            game.put("playTimes", playTimes[i]);
            game.put("popularityRate", popularityRates[i]);
            game.put("rank", i + 1);
            data.add(game);
        }

        return data;
    }

    /**
     * 获取实时动态
     */
    private List<Map<String, Object>> getRealtimeActivities() {
        List<Map<String, Object>> data = new ArrayList<>();

        String[] activities = {
            "用户小明与小红开始心动游戏",
            "北京用户成功匹配，开启聊天",
            "新用户小李完成个人资料认证",
            "上海地区新增VIP用户",
            "用户小王发布了新的动态",
            "深圳用户完成视频通话验证"
        };

        String[] times = {
            "刚刚",
            "1分钟前",
            "3分钟前",
            "5分钟前",
            "8分钟前",
            "10分钟前"
        };

        String[] types = {"游戏", "匹配", "注册", "付费", "社交", "认证"};

        for (int i = 0; i < activities.length; i++) {
            Map<String, Object> activity = new HashMap<>();
            activity.put("content", activities[i]);
            activity.put("time", times[i]);
            activity.put("type", types[i]);
            activity.put("typeCode", i % 4 + 1);
            data.add(activity);
        }

        return data;
    }

    /**
     * 获取社交网络数据
     */
    private Map<String, Object> getSocialNetworkData() {
        Map<String, Object> data = new HashMap<>();

        // 社交关系统计
        data.put("totalConnections", 8560000L); // 总连接数
        data.put("averageConnections", 3.3); // 平均每人连接数
        data.put("activeChats", 1250000L); // 活跃聊天数
        data.put("dailyMessages", 12580000L); // 日消息量

        // 互动质量分析
        Map<String, Object> interactionQuality = new HashMap<>();
        interactionQuality.put("responseRate", 78.5); // 回复率
        interactionQuality.put("averageResponseTime", 3.2); // 平均回复时间(分钟)
        interactionQuality.put("conversationLength", 15.8); // 平均对话长度
        interactionQuality.put("satisfactionScore", 4.3); // 满意度评分

        data.put("interactionQuality", interactionQuality);

        return data;
    }
}
